<template>
    <div class="m-spirit-wrapper" :style="'background-image:' + 'url('+ picList.spiritPage +')'">
        <div class="m-lucky-time" v-if="luckyShow">
            <div>
                <img :src="luckyTime" alt="">
                <span class="m-close-luckyTime" @click="closeLuckyTime"></span>
                <span class="m-lucky-message">{{ luckyMessage }}</span>
            </div>
        </div>
        <confirm v-model="showPayModal"
                 :title="'充值金额'"
                 :close-on-confirm="false"
                 @on-cancel="onCancel1"
                 @on-confirm="onConfirm1"
        >
            <selector :value="money" title="RMB" :options="moneyList" @on-change="onChange"></selector>
        </confirm>
        <confirm v-model="showExchangeModal"
                 :title="title"
                 :close-on-confirm="false"
                 @on-cancel="onCancel"
                 @on-confirm="onConfirm"
        >
            <group>
                <x-input title="兑换数量" v-model="count" type="number" placeholder="1到99之间的数量"></x-input>
            </group>
        </confirm>
        <confirm v-model="showCashModal"
                 :title="'金币提现(默认提现所有金币)'"
                 :close-on-confirm="false"
                 @on-cancel="onCancel2"
                 @on-confirm="onConfirm2"
        >
            <group>
                <x-input title="支付宝账号" v-model="account" placeholder="请输入支付宝账号"></x-input>
            </group>
        </confirm>
        <div class="m-property-info">
            <div class="m-left">
                <div class="m-gold" @click="cashModal">
                    <p>{{ userinfo.gold }}</p>
                </div>
                <div class="m-jewel" @click="payModal">
                    <p>{{ userinfo.jewel }}</p>
                </div>
            </div>
            <div class="m-right">
                <div class="m-red-energy" @click="showExchange(0)">
                    <p>{{userinfo.energyR }}</p>
                </div>
                <div class="m-blue-energy" @click="showExchange(1)">
                    <p>{{ userinfo.energyB }}</p>
                </div>
            </div>
        </div>
        <div class="m-spirit-modal" v-if="showDataFlag">
            <div class="m-spirit-info">
                <div class="m-avatar">
                    <img :src="userData.face" alt="">
                </div>
                <p class="m-info">{{ userData.username }}</p>
            </div>
            <img style="width:3rem;" v-if="showData.grade == 1" :src="spirit_icon_1" alt="">
            <img style="width:3rem;" v-if="showData.grade == 2" :src="spirit_icon_2" alt="">
            <img style="width:3rem;" v-if="showData.grade == 3" :src="spirit_icon_3" alt="">
            <img style="width:3rem;" v-if="showData.grade == 4" :src="spirit_icon_4" alt="">
        </div>
        <div class="m-spirit-content">
            <div class="m-energy-area" v-if="!noSpirit">
                <p class="timeRed" v-if="showDataFlag">{{ showData['timeRed'] ? showData['timeRed'] : 0 }}</p>
                <p class="timeBlue" v-if="showDataFlag">{{ showData['timeBlue'] ? showData['timeBlue'] : 0 }}</p>
                <span class="use-red-btn" @click="useEnergy(0)"></span>
                <span class="use-blue-btn" @click="useEnergy(1)"></span>
            </div>
            <div class="m-spirit-group">
                <div>
                    <i class="m-spirit" @click="uploading(1)"
                       :style="'background-image:' + 'url('+ picList.spirits[1] +')'"></i>
                    <p v-if="countDataFlag">{{ coutData['one'] }}</p>
                </div>
                <div>
                    <i class="m-spirit" @click="uploading(2)"
                       :style="'background-image:' + 'url('+ picList.spirits[2] +')'"></i>
                    <p v-if="countDataFlag">{{ coutData['two'] }}</p>
                </div>
                <div>
                    <i class="m-spirit" @click="uploading(3)"
                       :style="'background-image:' + 'url('+ picList.spirits[3] +')'"></i>
                    <p v-if="countDataFlag">{{ coutData['three'] }}</p>
                </div>
                <div>
                    <i class="m-spirit" @click="uploading(4)"
                       :style="'background-image:' + 'url('+ picList.spirits[4] +')'"></i>
                    <p v-if="countDataFlag">{{ coutData['four'] }}</p>
                </div>
            </div>
            <div class="progressContainer" v-if="!noSpirit">
                <div class="progress" :style="{width:percent +'%'}">
                </div>
            </div>
            <div class="m-btn" @click="supply" v-if="!noSpirit">
                补充
            </div>
        </div>
        <div class="m-goBack" @click="goBack"></div>
    </div>
</template>
<script>
import { picList } from "../config";

let wx = require("weixin-js-sdk");
import { XInput, Confirm, Group } from "vux";

export default {
  name: "Spirit",
  components: {
    XInput,
    Confirm,
    Group
  },
  data() {
    return {
      percent: 0,
      account: "",
      coutData: {},
      showData: {},
      token: "",
      noSpirit: false,
      ismy: false,
      no: null,
      pid: null,
      url: "",
      expMax: 0,
      exp: 0,
      showDataFlag: false,
      countDataFlag: false,
      title: "",
      spirit_icon_1: picList.spirits[1],
      spirit_icon_2: picList.spirits[2],
      spirit_icon_3: picList.spirits[3],
      spirit_icon_4: picList.spirits[4],
      shareToken: null,
      showExchangeModal: false,
      count: 1,
      userinfo: {
        id: "",
        jewel: 0,
        gold: 0,
        energyB: 0,
        energyR: 0
      },
      shareinfo: {},
      shareInfoExist: false,
      _location: "",
      token1: "xr5uGjGYbcqCXXUziqWOfzwPO14vMsM85SKPAnppkVQMjUHpW8yKyVZSnSou",
      token2: "XJ9GdyZ2QD6fLKSvlHFl8NVCY7dk9gH77BzP8BgRlvMDDH8qEicx5mOrpUjD",
      userData: {},
      userInfoExist: false,
      luckyTime: require("../assets/images/lucky_time.png"),
      luckyShow: false,
      luckyMessage: "",
      type: null,
      showPayModal: false,
      showCashModal: false,
      money: 0.01,
      moneyList: [10, 30, 50, 100]
    };
  },
  created() {
    this.pid = window.localStorage.getItem("pid")
      ? window.localStorage.getItem("pid")
      : null;
    this.userinfo = JSON.parse(window.localStorage.getItem("user"))
      ? JSON.parse(window.localStorage.getItem("user"))
      : {};
    this.url = "http://api.rjveg.pw/api/spirit?token=";
    this.token = window.localStorage.getItem("token");
    this.no = this.$route.params.no;
  },
  mounted() {
    this.getSpirit();
    // this.share();
    let link = "";
    let title = "标题";
    let self = this;
    this.$http
      .post("http://api.rjveg.pw/api/wechat/jssdk", { url: document.URL })
      .then(
        response => {
          let res = response.data;
          link = "http://"; // 链接
          let self = this;
          wx.config({
            debug: res.debug,
            appId: res.appId,
            timestamp: res.timestamp,
            nonceStr: res.nonceStr,
            signature: res.signature,
            jsApiList: res.jsApiList
          });
          wx.ready(function() {
            // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
            wx.onMenuShareTimeline({
              title: "h5game", // 分享标题
              link: `http://www.rjveg.pw/spirit/${self.no}?pId=${
                self.pid ? self.pid : self.userinfo.id
              }`, // 分享链接
              imgUrl: "",
              success: function() {
                // 用户确认分享后执行的回调函数
                // self.$http.post('/index.php/weixin/Share/link',{url: document.URL}).then((response) => {
                //     let res = response.data
                // }, (response) => {})
              },
              cancel: function() {
                // 用户取消分享后执行的回调函数
              }
            });
            // 朋友
            wx.onMenuShareAppMessage({
              title: "颗摇钱树", // 分享标题
              desc: "这是一颗摇钱树", // 分享描述
              imgUrl: "https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1530773607&di=9ba5ebc13ef5054405fa48a12c5b84c0&src=http://ec4.images-amazon.com/images/I/61DSnVLcs9L._SL1500_.jpg",
              link: `http://www.rjveg.pw/spirit/${self.no}?pId=${
                self.pid ? self.pid : self.userinfo.id
              }`, // 分享链接
              type: "link", // 分享类型,music、video或link，不填默认为link
              dataUrl: "", // 如果type是music或video，则要提供数据链接，默认为空
              success: function() {
                // 用户确认分享后执行的回调函数
                // self.$http.post('/index.php/weixin/Share/link', {url: document.URL}).then((response) => {
                //     let res = response.data
                //     if (res.code === '04') {
                //         return
                //     }
                // }, (response) => {})
              },
              cancel: function() {
                // 用户取消分享后执行的回调函数
                // console.log(link)
              }
            });
            wx.onMenuShareQQ({
              title: "摇钱树", // 分享标题
              desc: "这是一颗摇钱树", // 分享描述
              imgUrl: "",
              link: `http://www.rjveg.pw/spirit/${self.no}?pId=${
                self.pid ? self.pid : self.userinfo.id
              }`, // 分享链接
              success: function() {
                // 用户确认分享后执行的回调函数
              },
              cancel: function() {
                // 用户取消分享后执行的回调函数
              }
            });
          });
          wx.error(p => {
            console.log(p);
          });
        },
        response => {}
      );
  },
  methods: {
    showExchange(type) {
      this.showExchangeModal = true;
      this.type = type;
      this.title = this.type == 0 ? "兑换红色能量" : "兑换蓝色能量";
    },
    payModal() {
      this.showPayModal = true;
    },
    cashModal() {
      this.showCashModal = true;
    },
    onCancel2() {
      this.account = "";
    },
    onConfirm2() {
      if (
        /^0?(13[0-9]|15[012356789]|18[0123456789]|14[0123456789]|17[0123456789])[0-9]{8}$/.test(
          this.account
        )
      ) {
        this.$http
          .get(
            "http://api.rjveg.pw/api/user/withdraw?token=" +
              this.token +
              "&alipay=" +
              this.account
          )
          .then(res => {
            let data = res.data;
            if (data.code == 200) {
              this.$vux.toast.show({
                text: data.msg,
                type: "success",
                time: 2000
              });
              this.showCashModal = false;
            } else {
              this.$vux.toast.show({
                text: data.msg,
                type: "warn",
                time: 1000
              });
            }
          });
      } else if (
        /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(
          this.account
        )
      ) {
        this.$http
          .get(
            "http://api.rjveg.pw/api/user/withdraw?token=" +
              this.token +
              "&alipay=" +
              this.account
          )
          .then(res => {
            let data = res.data;
            if (data.code == 200) {
              this.$vux.toast.show({
                text: data.msg,
                type: "success",
                time: 2000
              });
              this.showCashModal = false;
            } else {
              this.$vux.toast.show({
                text: data.msg,
                type: "warn",
                time: 1000
              });
            }
          });
      } else {
        this.$vux.toast.show({
          text: "支付宝账号格式有误",
          type: "warn",
          time: 1000
        });
        return;
      }
    },
    onCancel1() {
      this.money = 1;
    },
    onConfirm1() {
      // let url1 = 'http://api.ittie.cn/pay_orderid?token=' + this.token1 + this.money;

      // this.$http.get(url1).then(res => {
      //     console.log(res);
      // });
      let configUrl =
        "http://api.rjveg.pw/api/wechat/pays?token=" +
        this.token +
        "&money=" +
        this.money;
      let url =
        "http://api.rjveg.pw/api/wechat?token=" +
        this.token +
        "&money=" +
        this.money;
      this.$http.get(configUrl).then(res => {
        let data = res.data;
        let config = data.config;
        let pay = data.pay;
        this.weixinPay(config);
      });
    },
    weixinPay(data) {
      var vm = this;
      if (typeof WeixinJSBridge == "undefined") {
        //微信浏览器内置对象。参考微信官方文档
        if (document.addEventListener) {
          document.addEventListener(
            "WeixinJSBridgeReady",
            vm.onBridgeReady(data),
            false
          );
        } else if (document.attachEvent) {
          document.attachEvent("WeixinJSBridgeReady", vm.onBridgeReady(data));
          document.attachEvent("onWeixinJSBridgeReady", vm.onBridgeReady(data));
        }
      } else {
        vm.onBridgeReady(data);
      }
    },
    onBridgeReady: function(data) {
      var vm = this;
      WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          debug: true,
          appId: data.appId, //公众号名称，由商户传入
          timeStamp: data.timeStamp, //时间戳，自1970年以来的秒数
          nonceStr: data.nonceStr, //随机串
          package: data.package,
          signType: data.signType, //微信签名方式：
          paySign: data.paySign //微信签名
          //这里的信息从后台返回的接口获得。
        },
        function(res) {
          // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            if (vm.fromRoute == "personal") {
              window.location.href = document.URL;
            } else {
              // vm.confirmTry();
            }
          } else {
            alert("取消支付！");
          }
        }
      );
    },
    onCancel() {
      this.count = 1;
    },
    onConfirm() {
      if (!/^[1-9][0-9]?$/.test(this.count)) {
        this.$vux.toast.show({
          text: "数量1到99之间",
          type: "warn",
          time: 1000
        });
      } else {
        var params = new URLSearchParams();
        params.append("token", this.token);
        params.append("type", this.type);
        params.append("number", this.count);
        this.$http({
          method: "post",
          url: "http://api.rjveg.pw/api/property/exchange",
          data: params
        }).then(res => {
          let data = res.data;
          if (data.code == 200) {
            this.$vux.toast.show({
              text: data.msg,
              type: "success",
              time: 1000
            });
            this.showExchangeModal = false;
            this.count = 1;
            this.getOwnProperty();
          } else {
            this.$vux.toast.show({
              text: data.msg,
              type: "warn",
              time: 1000
            });
          }
        });
      }
    },
    onChange(val) {
      this.money = val;
    },
    enCodeLocalUrl(url) {
      return window.encodeURIComponent(url); // url必须动态获取，不能缓存
    },
    closeLuckyTime() {
      this.luckyShow = false;
    },
    share() {
      let link = this.enCodeLocalUrl(
        window.location.href.split("#")[0] + "?pId=" + this.pid
          ? this.pid
          : this.userinfo.id
      );
      this.wxShare(
        "精灵",
        "精灵页面",
        link,
        "https://o3e85j0cv.qnssl.com/tulips-1083572__340.jpg"
      );
    },
    goBack() {
      this.$router.go(-1);
    },
    getSpirit() {
      this.$http
        .get(this.url + this.token + "&pId=" + this.pid + "&island=" + this.no)
        .then(res => {
          this.coutData = res.data.data.coutData;
          this.showData = res.data.data.showData;
          this.userData = res.data.data.userdata;
          this.countDataFlag = Object.keys(this.coutData).length > 0;
          if (this.showData == null) {
            this.showDataFlag = false;
          } else {
            this.showDataFlag = Object.keys(this.showData).length > 0;
            this.expMax = parseInt(this.showData.expMax);
            this.exp = parseInt(this.showData.exp);
            this.percent = this.exp / this.expMax * 100;
          }
          this.ismy = res.data.data.ismy;
          let num = 0;
          for (let k in this.coutData) {
            num += this.coutData[k];
          }
          if (num === 0 || !this.showDataFlag) {
            this.noSpirit = true;
          }
          if (this.showDataFlag) {
            this.noSpirit = false;
          }
        });
    },
    useEnergy(type) {
      if (!this.ismy) {
        let url = "http://api.rjveg.pw/api/energy/use?token=" + this.token;
        this.$http
          .get(
            url +
              "&type=" +
              type +
              "&spiritsId=" +
              this.showData.id +
              "&pId=" +
              this.pid
          )
          .then(res => {
            let data = res.data;
            if (data.code == 200) {
              if (data.msg.isShow) {
                this.luckyShow = true;
                this.$vux.toast.show({
                  text: data.msg.msgShow,
                  type: "success",
                  time: 1000
                });
                this.luckyMessage = data.msg.msgShow;
              }
              this.$vux.toast.show({
                text: data.msg.msg,
                type: "success",
                time: 1000
              });
              this.getSpirit();
              this.getOwnProperty();
            }
            if (data.code == 400) {
              this.$vux.toast.show({
                text: data.msg,
                type: "warn",
                time: 1000
              });
            }
          });
      } else {
        this.$vux.toast.show({
          text: "自己不能给自己补充哦",
          type: "warn",
          time: 1000
        });
      }
    },
    getOwnProperty() {
      let url = `http://api.rjveg.pw/api/user/property?token=` + this.token;
      this.$http.get(url).then(res => {
        let data = res.data.data;
        this.userinfo.gold = data.gold;
        this.userinfo.energyR = data.energyR;
        this.userinfo.energyB = data.energyB;
        this.userinfo.jewel = data.jewel;
      });
    },
    addSpirit() {
      let url = "http://www.rjveg.pw/api/spirit/addadd?token=" + this.token;
      this.$http.get(url).then(res => {});
    },
    uploading(grade) {
      if (this.ismy) {
        let url =
          "http://api.rjveg.pw/api/spirit/uploading?token=" + this.token;
        this.$http
          .get(url + "&grade=" + grade + "&island=" + this.$route.params.no)
          .then(res => {
            let data = res.data;
            if (data.code == 400) {
              this.$vux.toast.show({
                text: data.msg,
                type: "warn",
                time: 1000
              });
            } else {
              this.$vux.toast.show({
                text: data.msg,
                type: "success",
                time: 1000
              });
              this.getSpirit();
            }
          });
      } else {
        this.$vux.toast.show({
          text: "这不是你的精灵",
          type: "warn",
          time: 1000
        });
      }
    },
    supply() {
      if (this.percent === 100) {
        this.$vux.toast.show({
          text: "能量已满",
          position: "default",
          type: "warn"
        });
        setTimeout(() => {
          this.$vux.toast.hide();
        }, 5000);
        return;
      }
      this.percent++;
    }
  }
};
</script>

<style scoped lang="less">
.m-lucky-time {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  z-index: 999;
  .m-lucky-message {
    position: absolute;
    width: 100%;
    bottom: 0.6rem;
    left: 60%;
    font-size: 0.3rem;
    color: #fff;
    transform: translate(-50%, -50%);
  }
  & > div {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
  img {
    width: 5rem;
  }
  .m-close-luckyTime {
    position: absolute;
    width: 1rem;
    height: 1rem;
    right: -0.1rem;
    top: 0.5rem;
    z-index: 9;
  }
}

.use-red-btn,
.use-blue-btn {
  position: absolute;
  width: 2rem;
  height: 0.7rem;
  display: inline-block;
  right: 0;
}

.use-red-btn {
  top: 0.3rem;
}

.use-blue-btn {
  top: 1rem;
}

.m-spirit-modal {
  height: 5rem;
  text-align: center;
  position: relative;
  .m-spirit-info {
    position: absolute;
    left: 50%;
    top: -1.5rem;
    transform: translate(-50%, -50%);
    img {
      width: 1.5rem;
      height: 1.5rem;
      border-radius: 50%;
    }
    font-size: 0.3rem;
  }
}

.weui-toast {
  min-height: auto;
}

.m-spirit-group {
  display: flex;
  & > div {
    flex: 1;
    text-align: center;
    color: #fff;
    font-size: 0.35rem;
    font-weight: 700;
  }
  .m-spirit {
    width: 2rem;
    height: 2rem;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    display: inline-block;
  }
  /*& > div:nth-child(1) .m-spirit {*/
  /*background-image: url("../assets/images/spirit_icon_1.png");*/
  /*}*/
  /*& > div:nth-child(2) .m-spirit {*/
  /*background-image: url("../assets/images/spirit_icon_2.png");*/
  /*}*/
  /*& > div:nth-child(3) .m-spirit {*/
  /*background-image: url("../assets/images/spirit_icon_3.png");*/
  /*}*/
  /*& > div:nth-child(4) .m-spirit {*/
  /*background-image: url("../assets/images/spirit_icon_4.png");*/
  /*}*/
}

.m-spirit-content {
  position: absolute;
  left: 50%;
  top: 8rem;
  transform: translateX(-50%);
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  align-items: center;
}

.m-spirit-wrapper {
  width: 100%;
  height: 100%;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  position: relative;
  .m-goBack {
    width: 1.5rem;
    height: 1.5rem;
    position: absolute;
    bottom: 0.7rem;
    left: 0.1rem;
    background-image: url("../assets/images/back_icon.png");
    background-repeat: no-repeat;
    background-size: 100% 100%;
  }
}

.m-energy-area {
  width: 500/75rem;
  height: 150/75rem;
  background-image: url("../assets/images/energy_area_icon.png");
  background-repeat: no-repeat;
  background-size: 100% 100%;
  position: relative;
  .timeRed,
  .timeBlue {
    position: absolute;
    left: 2rem;
    color: #fff;
    font-weight: 700;
    font-size: 0.3rem;
  }
  .timeRed {
    top: 0.4rem;
  }
  .timeBlue {
    top: 1.1rem;
  }
}

.m-btn {
  width: 200/75rem;
  height: 1rem;
  line-height: 1rem;
  text-align: center;
  font-size: 0.4rem;
  color: #fff;
  margin-top: 0.5rem;
  background-image: url("../assets/images/button_icon.png");
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
</style>
